import { request } from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
   /**
   * 页面的初始数据
   */
  data: {
    goods:[],
    isCollect:false
  },
  GoodsList:[],
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let currentPages =  getCurrentPages();
    const options =  currentPages[currentPages.length-1].options;   
    const {goods_id} = options;
    this.getDetailList(goods_id);
  },
  //点击收藏
  handCollect(){
    let isCollect= false;
    let collect = wx.getStorageSync('collect')||[];
    let index = collect.findIndex(v=>v.goods_id===this.GoodsList.goods_id);
    if(index==-1){
      //说明没有收藏，就收藏
      collect.push(this.GoodsList);
      wx.showToast({
        title: '收藏成功',
        icon: 'sueecss',
        mask: false,
      }); 
      isCollect = true;
    }else{
      //已经收藏过了，取消收藏
      collect.splice(index,1);
      wx.showToast({
        title: '取消收藏',
        mask: false,
      }); 
      isCollect = false
    }
    this.setData({
      isCollect
    })
    wx.setStorageSync('collect',collect);
  },
  //获取商品详情页面
  async getDetailList(goods_id){
    const res = await request({url:'/goods/detail?',data:{goods_id}})
    this.GoodsList = res;
    //获取缓存中的收藏数组
    let collect = wx.getStorageSync('collect')||[];
    let isCollect = collect.some(v=>v.goods_id===this.GoodsList.goods_id);
    this.setData({
      goods:{
        goods_name:res.goods_name,
        goods_price:res.goods_price,
        //部分苹果手机不支持webp格式的图片，通知后台去改
        pics:res.pics,
        goods_introduce:res.goods_introduce.replace(/\.webp/g,'.jpg'),
      },
      isCollect
    })
  },
  //点击预览轮播图图片
  handleSwiperItem(e){
    const urls = this.GoodsList.pics.map(v=>v.pics_mid);
    //console.log (e);
    const {current} = e.currentTarget.dataset
    wx.previewImage({
      current,
      urls
    });
      
  },
  //点击加入购物车
  handleCarAdd(){
   //1.获取缓存中的购物车 数组
    let cart = wx.getStorageSync('cart')||[];
    //2.判断商品对象是否存在于购物车中
    let index = cart.findIndex(v=>v.goods_id===this.GoodsList.goods_id);
    if(index===-1){
      //3.说明不存在  第一次添加  数量为1
      this.GoodsList.num=1;
      this.GoodsList.checked=true;
      cart.push(this.GoodsList);
    }else{
      //4.已经存在，商品的数量+1
      cart[index].num++;
    }
    //5.数据保存到本地缓存中
    wx.setStorageSync('cart', cart);
    //6.提示成功消息
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true,
    }); 
  }
})